package com.kangfu.wechat.api;

import com.alibaba.druid.support.json.JSONUtils;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.wechat.bean.request.GenerateschemeRequest;
import com.kangfu.wechat.bean.result.Token;
import com.kangfu.wechat.bean.result.Urlscheme;
import com.kangfu.wechat.utils.JsonUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class UrlschemeApi extends BaseApi  {

    private static final Logger logger = LoggerFactory.getLogger(TokenApi.class);

    public static String getUrlscheme(String appid, String secret) {
        Token token = TokenApi.getToken(appid, secret);
        String url = BASE_URI + "/wxa/generatescheme?access_token=" + token.getAccess_token();

        //构建请求body
        GenerateschemeRequest.JumpWxaBean jumpWxaBean = new GenerateschemeRequest.JumpWxaBean();
        jumpWxaBean.setPath("pages/home/index");
        GenerateschemeRequest generateschemeRequest = new GenerateschemeRequest();
        generateschemeRequest.setExpire_type(1);
        generateschemeRequest.setExpire_interval(30);
        generateschemeRequest.setJump_wxa(jumpWxaBean);
        String jsonStr = JsonUtil.toJSONString(generateschemeRequest);
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonStr);

        OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
        Request request = new Request.Builder().url(url).post(body).build();
        try{
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) { // 判断是否成功
                String string = response.body().string();
                logger.info("generatescheme response: " + string);
                Urlscheme urlscheme = JsonUtil.parseObject(string, Urlscheme.class);
                if (urlscheme == null) {
                    throw new BusinessException("geturlscheme 失败");
                }
                return urlscheme.getOpenlink();
            } else {
                logger.error("获取用户手机号 失败 : code : " + response.code() + " || message : " + response.message());
                throw new BusinessException("geturlscheme 失败");
            }
        } catch (Exception e){
            logger.error("获取用户手机号 失败 : " + e.getMessage());
            throw new BusinessException("geturlscheme 失败");
        }

    }
}
